<template>
  <div class="app-container">
    <!-- 修改高级查询下拉框配置 -->
    <el-dropdown trigger="click" :hide-on-click="false">
      <el-button type="primary">
        高级查询<el-icon class="el-icon--right"><arrow-down /></el-icon>
      </el-button>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item :hide-on-click="false">
            <!-- 其余表单内容保持不变 -->
            <el-form
              :model="queryParams"
              ref="queryRef"
              :inline="true"
              label-width="60px"
              @click.stop
            >
              <el-form-item label="存货编号" prop="inventoryCode">
                <el-input
                  v-model="queryParams.inventoryCode"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
              <br />
              <el-form-item label="存货名称" prop="inventoryName">
                <el-input
                  v-model="queryParams.inventoryName"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
              <br />

              <el-form-item
                label="存货分类"
                prop="inventoryCategory"
                style="width: 100%"
              >
                <el-select
                  v-model="queryParams.inventoryCategory"
                  placeholder="请选择存货分类"
                  clearable
                >
                  <el-option label="工业原料" value="工业原料" />
                  <el-option label="化工产品" value="化工产品化工产品" />
                  <el-option label="机械设备配件" value="机械设备配件" />
                  <el-option label="电子元器件" value="电子元器件" />
                  <el-option label="消费品" value="消费品" />
                  <el-option label="食品原料" value="食品原料" />
                  <el-option label="医疗用品" value="医疗用品" />
                  <el-option label="建筑材料" value="建筑材料" />
                  <el-option label="服装和纺织品" value="服装和纺织品" />
                  <el-option label="农副产品" value="农副产品" />
                </el-select>
              </el-form-item>
              <br />
              <el-form-item
                label="存货类型"
                prop="inventoryType"
                style="width: 80%"
              >
                <el-select
                  v-model="queryParams.inventoryType"
                  placeholder="请选择存货类型"
                  clearable
                >
                  <el-option label="原材料" value="原材料" />
                  <el-option label="在产品" value="在产品" />
                  <el-option label="半成品" value="半成品" />
                  <el-option label="产成品" value="产成品" />
                  <el-option label="商品以" value="商品以" />
                  <el-option label="周转材料" value="周转材料" />
                  <el-option label="委托代销商品" value="委托代销商品" />
                  <el-option label="预付贷款" value="预付贷款" />
                  <el-option label="在途物资" value="在途物资" />
                  <el-option label="库存材料" value="库存材料" />
                  <el-option
                    label="其他固委托代销商品定资产"
                    value="其他固委托代销商品定资产"
                  />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
              <br />
              <el-form-item label="状态" prop="status" style="width: 100%">
                <el-select
                  v-model="queryParams.status"
                  placeholder="全部"
                  clearable
                >
                  <el-option label="是" value="是" />
                  <el-option label="否" value="否" />
                </el-select>
              </el-form-item>
              <br />
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery"
                  >查询</el-button
                >
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <!-- 原有的表单部分可以保留或根据需要隐藏 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="存货编号" prop="inventoryCode">
        <el-input
          v-model="queryParams.inventoryCode"
          placeholder="请输入存货编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 修改按钮布局部分 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="20">
        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-col>
      <el-col :span="4" style="text-align: right">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['InventoryInfo:InventoryInfo:add']"
          >新增</el-button
        >
        <el-button
          type="danger"
          plain
          icon="Delete"
          @click="handleDelete"
          v-hasPermi="['InventoryInfo:InventoryInfo:remove']"
          >删除</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="InventoryInfoList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" fixed />
      <el-table-column
        label="存货编号"
        align="center"
        prop="inventoryCode"
        fixed="fixed"
      />
      <el-table-column label="存货名称" align="center" prop="inventoryName" />
      <el-table-column label="规格型号" align="center" prop="specModel" />
      <el-table-column label="存货类型" align="center" prop="inventoryType" />
      <el-table-column
        label="存货分类"
        align="center"
        prop="inventoryCategory"
      />
      <el-table-column label="计价方式" align="center" prop="pricingMethod" />
      <el-table-column label="主单位" align="center" prop="mainUnit" />
      <el-table-column label="当前库存" align="center" prop="currentStock" />
      <el-table-column label="最低库存" align="center" prop="minStock" />
      <el-table-column label="最高库存" align="center" prop="maxStock" />
      <el-table-column label="安全库存" align="center" prop="safetyStock" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="商品用途" align="center" prop="commodityUsage" />
      <el-table-column label="备注" align="center" prop="remarks" />
      <el-table-column label="计量单位" align="center" prop="measurementUnit" />
      <el-table-column label="采购价" align="center" prop="purchasePrice" />
      <el-table-column label="销售价" align="center" prop="sellingPrice" />
      <el-table-column label="成本价" align="center" prop="costPrice" />
      <el-table-column
        label="支出多计量单位"
        align="center"
        prop="multiMeasurementUnit"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['InventoryInfo:InventoryInfo:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['InventoryInfo:InventoryInfo:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改存货信息对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form
        ref="InventoryInfoRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <div style="font-weight: bold; margin-bottom: 15px">基本信息</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="存货编号" prop="inventoryCode">
              <el-input v-model="form.inventoryCode" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存货名称" prop="inventoryName">
              <el-input v-model="form.inventoryName" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specModel">
              <el-input v-model="form.specModel" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存货类型" prop="inventoryType">
              <el-select
                v-model="form.inventoryType"
                placeholder="请选择存货类型"
                style="width: 100%"
              >
                <el-option label="原材料" value="原材料" />
                <el-option label="在产品" value="在产品" />
                <el-option label="半成品" value="半成品" />
                <el-option label="产成品" value="产成品" />
                <el-option label="商品以" value="商品以" />
                <el-option label="周转材料" value="周转材料" />
                <el-option label="委托代销商品" value="委托代销商品" />
                <el-option label="预付贷款" value="预付贷款" />
                <el-option label="在途物资" value="在途物资" />
                <el-option label="库存材料" value="库存材料" />
                <el-option
                  label="其他固委托代销商品定资产"
                  value="其他固委托代销商品定资产"
                />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="存货分类" prop="inventoryCategory">
              <el-select
                v-model="form.inventoryCategory"
                placeholder="请选择存货分类"
                style="width: 100%"
              >
                <el-option label="工业原料" value="工业原料" />
                <el-option label="化工产品" value="化工产品" />
                <el-option label="商品以" value="商品以" />
                <el-option label="周转材料" value="周转材料" />
                <el-option label="委托代销商品" value="委托代销商品" />
                <el-option label="预付贷款" value="预付贷款" />
                <el-option label="在途物资" value="在途物资" />
                <el-option label="库存材料" value="库存材料" />
                <el-option
                  label="其他固委托代销商品定资产"
                  value="其他固委托代销商品定资产"
                />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计价方式" prop="pricingMethod">
              <el-select
                v-model="form.pricingMethod"
                placeholder="请选择计价方式"
                style="width: 100%"
              >
                <el-option label="先进先出" value="先进先出" />
                <el-option label="移动平均" value="移动平均" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="是">是</el-radio>
                <el-radio label="否">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品用途" prop="commodityUsage">
              <el-checkbox v-model="form.commodityUsage" label="开票商品"
                >开票商品</el-checkbox
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="form.remarks"
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>

        <div style="font-weight: bold; margin: 20px 0 15px">存货单位</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计量单位" prop="measurementUnit">
              <el-select
                v-model="form.measurementUnit"
                placeholder="请选择计量单位"
                style="width: 100%"
              >
                <el-option label="米" value="米" />
                <el-option label="千克" value="千克" />
                <el-option label="个" value="个" />
                <el-option label="件" value="件" />
                <el-option label="包" value="包" />
                <el-option label="双" value="双" />
                <el-option label="台" value="台" />
                <el-option label="套" value="套" />
                <el-option label="手" value="手" />
                <el-option label="条" value="条" />
                <el-option label="瓶" value="瓶" />
                <el-option label="盒" value="盒" />
                <el-option label="箱" value="箱" />
                <el-option label="袋" value="袋" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购价" prop="purchasePrice">
              <el-input v-model="form.purchasePrice" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="销售价" prop="sellingPrice">
              <el-input v-model="form.sellingPrice" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成本价" prop="costPrice">
              <el-input v-model="form.costPrice" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最低库存" prop="minStock">
              <el-input v-model="form.minStock" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最高库存" prop="maxStock">
              <el-input v-model="form.maxStock" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="安全库存" prop="safetyStock">
              <el-input v-model="form.safetyStock" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前库存" prop="currentStock">
              <el-input v-model="form.currentStock" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="期末结存存货成本" prop="qmPrice">
              <el-input v-model="form.qmPrice" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="期初结存存货成本" prop="qcPrice">
              <el-input v-model="form.qcPrice" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="当期购进存货成本" prop="dqPrice">
              <el-input v-model="form.dqPrice" placeholder="请输入" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当期发出存货成本" prop="fcPrice">
              <el-input v-model="form.fcPrice" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="InventoryInfo">
import {
  listInventoryInfo,
  getInventoryInfo,
  delInventoryInfo,
  addInventoryInfo,
  updateInventoryInfo,
} from "@/api/InventoryInfo/InventoryInfo";

const { proxy } = getCurrentInstance();

const InventoryInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    inventoryCode: null,
    inventoryName: null,
    inventoryType: null,
    inventoryCategory: null,
    safetyStock: null,
    status: null,
  },
  rules: {
    inventoryCode: [
      { required: true, message: "存货编号不能为空", trigger: "blur" },
    ],
    inventoryName: [
      { required: true, message: "存货名称不能为空", trigger: "blur" },
    ],
    measurementUnit: [
      { required: true, message: "计量单位不能为空", trigger: "change" },
    ],
    purchasePrice: [
      { required: true, message: "采购价不能为空", trigger: "blur" },
    ],
    sellingPrice: [
      { required: true, message: "销售价不能为空", trigger: "blur" },
    ],
    costPrice: [{ required: true, message: "成本价不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询存货信息列表 */
function getList() {
  loading.value = true;
  listInventoryInfo(queryParams.value).then((response) => {
    InventoryInfoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    inventoryCode: null,
    inventoryName: null,
    specModel: null,
    inventoryType: null,
    inventoryCategory: null,
    pricingMethod: null,
    mainUnit: null,
    currentStock: 20, // 设置默认值为20
    minStock: null,
    maxStock: null,
    safetyStock: null,
    status: null,
    commodityUsage: null,
    remarks: null,
    measurementUnit: null,
    purchasePrice: null,
    sellingPrice: null,
    costPrice: null,
    multiMeasurementUnit: null,
    qmPrice: null,
    qcPrice: null,
    dqPrice: null,
    fcPrice: null,
  };
  proxy.resetForm("InventoryInfoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
// ... 在 script setup 部分修改 watch 函数
watch(
  [() => form.value.currentStock, () => form.value.costPrice],
  ([newCurrentStock, newCostPrice]) => {
    if (newCurrentStock && newCostPrice) {
      // 计算当期购进存货成本
      form.value.dqPrice = Number(newCurrentStock) * Number(newCostPrice);
    }
  }
);

// 监听期初结存、当期购进和当期发出存货成本的变化，计算期末结存存货成本
watch(
  [() => form.value.qcPrice, () => form.value.dqPrice, () => form.value.fcPrice],
  ([newQcPrice, newDqPrice, newFcPrice]) => {
    // 计算期末结存存货成本
    form.value.qmPrice = 
      (Number(newQcPrice) || 0) + 
      (Number(newDqPrice) || 0) - 
      (Number(newFcPrice) || 0);
  }
);

// ... 其他代码保持不变

/** 生成存货编号 */
function generateInventoryCode() {
  const date = new Date();
  const year = date.getFullYear();
  const month = String.fromCharCode(65 + date.getMonth()); // 将月份转换为A-L
  const sequence = String(InventoryInfoList.value.length + 1).padStart(3, "0");
  return `STOCK-${year}${month}${sequence}`;
}

// 修改 handleAdd 方法
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加存货信息";
  // 自动生成存货编号
  form.value.inventoryCode = generateInventoryCode();
}

// 在表单中修改存货编号输入框

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getInventoryInfo(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改存货信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["InventoryInfoRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateInventoryInfo(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addInventoryInfo(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除存货信息编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delInventoryInfo(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "InventoryInfo/InventoryInfo/export",
    {
      ...queryParams.value,
    },
    `InventoryInfo_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style scoped>
.el-dropdown {
  margin-bottom: 0;
}
</style>
